﻿using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;

public class TestAsync : MonoBehaviour
{
    private CancellationTokenSource _sayHelloTokenSource;
    private void Start()
    {
        _sayHelloTokenSource = new CancellationTokenSource();

        PrintMessageDelayNotAsync(2000, "Hi, I am a dog.");

        PrintMessageDelay(4000, "Hi, I am a cat.", _sayHelloTokenSource);       

        CancelTokenSource(2000, _sayHelloTokenSource);
        
        Debug.Log("Start" + "," + Time.time);
    }

    private void PrintMessageDelayNotAsync(int ms, string message)
    {
        try
        {
            Task.Delay(ms);
            //会无视Delay，直接打印信息
            Debug.Log(message);
        }
        catch (Exception e)
        {
            Debug.LogErrorFormat("Exception : {0} - {1}", e.HResult, e.Message);
        }
    }

    //要加await关键字，方法必须加了async
    private async void PrintMessageDelay(int ms, string message, CancellationTokenSource tokenSource)
    {
        try
        {
            await Task.Delay(ms, tokenSource.Token);

            if (!tokenSource.IsCancellationRequested)
            {
                Debug.Log(message);
            }
        }
        catch (Exception e)
        {
            Debug.LogErrorFormat("Exception : {0} - {1}", e.HResult, e.Message);
        }        
    }

    private async void CancelTokenSource(int ms, CancellationTokenSource tokenSource)
    {
        await Task.Delay(ms);

        Debug.LogFormat("Cancel TokenSource : ", Time.time);

        tokenSource.Cancel();
    }

}
